package main

import (
	"bufio"
	"encoding/csv"
	"flag"
	"fmt"
	"os"
	"regexp"
	"strings"
)

type EEntry struct {
	Date      string
	Plate     string
	Interface string
	Error     string
}

var codePattern = regexp.MustCompile(`(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}) (.*?): (.*?), failed: (\d+)`)

// analyzeErrCode 对每一行进行分析
func analyzeErrCode(line string, logEntries *[]EEntry) {
	matches := codePattern.FindStringSubmatch(line)
	if matches != nil {
		entry := EEntry{
			Date:      matches[1],
			Plate:     matches[2],
			Interface: matches[3],
			Error:     matches[4],
		}
		*logEntries = append(*logEntries, entry)
	}
}

func main() {
	// 定义命令行参数
	filePath := flag.String("file", "", "Path to the file to be analyzed")
	flag.Parse()

	if *filePath == "" {
		fmt.Println("Please provide a file path using the -file flag.")
		return
	}

	file, err := os.Open(*filePath)
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	defer file.Close()

	var logEntries []EEntry
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		analyzeErrCode(line, &logEntries)
	}

	if err := scanner.Err(); err != nil {
		fmt.Println("Error reading file:", err)
	}

	// 生成分析表格并保存到CSV文件
	outputFilePath := strings.TrimSuffix(*filePath, ".txt") + "_analysis.csv"
	outputFile, err := os.Create(outputFilePath)
	if err != nil {
		fmt.Println("Error creating output file:", err)
		return
	}
	defer outputFile.Close()

	writer := csv.NewWriter(outputFile)
	defer writer.Flush()

	// 写入表头
	if err := writer.Write([]string{"Date", "Plate", "Interface", "Error"}); err != nil {
		fmt.Println("Error writing CSV header:", err)
		return
	}

	// 写入每一行数据
	for _, entry := range logEntries {
		if err := writer.Write([]string{entry.Date, entry.Plate, entry.Interface, entry.Error}); err != nil {
			fmt.Println("Error writing CSV row:", err)
			return
		}
	}

	fmt.Printf("Analysis saved to %s\n", outputFilePath)
}
